package com.zoran.study.spring.validation.validator;


import com.zoran.study.spring.validation.constraint.CellPhone;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Validates cell phone number against the {@link CellPhone#pattern pattern}.
 *
 * @author Winter Gao
 *
 */
public class CellPhoneValidator implements ConstraintValidator<CellPhone, String> {

    private Pattern pattern;

    @Override
    public void initialize(CellPhone constraintAnnotation) {
        pattern = Pattern.compile(constraintAnnotation.pattern());
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }

        Matcher m = pattern.matcher(value);
        return m.matches();
    }

}
